// 主进程与渲染进程的沟通工具contextBridge
const { ipcRenderer, remote, contextBridge, clipboard } = require('electron')

// 需要引入的包
const fs = require("fs")
const path = require("path")

console.log("preload.js is called");
// 向渲染进程传输
contextBridge.exposeInMainWorld("myApi", {
    fs,
    path,
    dirName: __dirname, jsonPath: path.join(
        __dirname,
        "../store/navigation.json"
    ),
    copyFileWithProgress,
    ipcRenderer,
    clipboard
})

ipcRenderer.on('app-path', (event, appPath) => {
    // 在这里可以使用 appPath，例如构建图片的绝对路径
    // const imagePath = path.join(appPath, 'path/to/your/image.jpg');
    console.log(appPath);

    // 将图片路径传递给前端的代码，例如通过 Vue 或 React 的状态
    // 然后在模板中使用相应的路径来显示图片
    // 请根据你的具体前端框架和代码结构进行调整
});

// 使用文件流传输数据
function copyFileWithProgress(source, target, fun) {
    return new Promise((resolve, reject) => {
        const readStream = fs.createReadStream(source);
        const writeStream = fs.createWriteStream(target);
        let totalBytesCopied = 0;
        let totalBytes = 0;

        // 获取源文件大小python-script-result
        fs.stat(source, (err, stats) => {
            if (err) {
                reject(err);
                return;
            }
            totalBytes = stats.size;
        });

        readStream.on('data', (chunk) => {
            totalBytesCopied += chunk.length;
            const progress = (totalBytesCopied / totalBytes) * 100;
            fun(progress.toFixed(0))
        });

        readStream.on('error', (err) => {
            reject(err);
        });

        writeStream.on('error', (err) => {
            reject(err);
        });

        writeStream.on('finish', () => {
            resolve();
        });

        readStream.pipe(writeStream);
    });
}

